/*
 * Copyright (c) 2018-2999 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.lam.common.components.redis.CacheManagerUtil;
import com.lam.common.exception.BusinessException;
import com.lam.common.utils.NumberUtil;
import com.lam.mall.app.param.ChangeShopCartParam;
import com.lam.mall.app.param.OrderItemParam;
import com.lam.mall.app.param.ShopCartParam;
import com.lam.mall.app.vo.ShopCartItemVo;
import com.lam.mall.app.vo.ShopCartVo;
import com.lam.mall.common.event.ShopCartEvent;
import com.lam.mall.entity.Basket;
import com.lam.mall.entity.ProdSku;
import com.lam.mall.entity.Product;
import com.lam.mall.entity.ShopDetail;
import com.lam.mall.mapper.BasketMapper;
import com.lam.mall.service.BasketService;
import com.lam.mall.service.ProdSkuService;
import com.lam.mall.service.ProductService;
import com.lam.mall.service.ShopDetailService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

/**
 */
@Service
public class BasketServiceImpl implements BasketService {

	@Autowired
    private  BasketMapper basketMapper;
	@Autowired
    private  CacheManagerUtil cacheManagerUtil;
	@Autowired
    private  ApplicationContext applicationContext;
	@Autowired
    private  ProdSkuService prodSkuService;
	@Autowired
    private  ShopDetailService shopDetailService;
	@Autowired
    private  ProductService productService;

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void deleteShopCartItemsByBasketIds(String userId, List<String> basketIds) {
        basketMapper.deleteShopCartItemsByBasketIds(userId, basketIds);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void addShopCartItem(ChangeShopCartParam param, String userId) {
        Basket basket = new Basket();
        basket.setBasketCount(param.getCount());
        basket.setBasketDate(new Date());
        basket.setProdId(param.getProdId());
        basket.setShopId(param.getShopId());
        basket.setUserId(userId);
        basket.setSkuId(param.getSkuId());
        basket.setDistributionCardNo(param.getDistributionCardNo());
        basketMapper.insert(basket);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#basket.userId")
    public void updateShopCartItem(Basket basket) {
        basketMapper.updateById(basket);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void deleteAllShopCartItems(String userId) {
        basketMapper.deleteAllShopCartItems(userId);
    }

    @Override
    public List<ShopCartItemVo> getShopCartItems(String userId) {
        // 在这个类里面要调用这里的缓存信息，并没有使用aop，所以不使用注解
        List<ShopCartItemVo> shopCartItemVoList = cacheManagerUtil.getCache("ShopCartItems", userId);
        if (shopCartItemVoList != null) {
            return shopCartItemVoList;
        }
        shopCartItemVoList = basketMapper.getShopCartItems(userId);
        for (ShopCartItemVo shopCartItemVo : shopCartItemVoList) {
            shopCartItemVo.setProductTotalAmount(NumberUtil.multiply(new BigDecimal(shopCartItemVo.getProdCount()), shopCartItemVo.getPrice()));
        }
        cacheManagerUtil.putCache("ShopCartItems", userId, shopCartItemVoList);
        return shopCartItemVoList;
    }

    @Override
    public List<ShopCartItemVo> getShopCartExpiryItems(String userId) {
        return basketMapper.getShopCartExpiryItems(userId);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void cleanExpiryProdList(String userId) {
        basketMapper.cleanExpiryProdList(userId);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void updateBasketByShopCartParam(String userId, Map<String, ShopCartParam> basketIdShopCartParamMap) {
        basketMapper.updateDiscountItemId(userId, basketIdShopCartParamMap);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void removeShopCartItemsCacheByUserId(String userId) {
    	cacheManagerUtil.evictCache("ShopCartItems", userId);
    }

    @Override
    public List<String> listUserIdByProdId(String prodId) {
        return basketMapper.listUserIdByProdId(prodId);
    }

    @Override
    public List<ShopCartVo> getShopCarts(List<ShopCartItemVo> shopCartItems) {
        // 根据店铺ID划分item
        Map<String, List<ShopCartItemVo>> shopCartMap = shopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemVo::getShopId));

        // 返回一个店铺的所有信息
        List<ShopCartVo> shopCartVos = new ArrayList<>();
        for (String shopId : shopCartMap.keySet()) {

            //获取店铺的所有商品项
            List<ShopCartItemVo> shopCartItemVoList = shopCartMap.get(shopId);

            // 构建每个店铺的购物车信息
            ShopCartVo shopCart = new ShopCartVo();

            //店铺信息
            shopCart.setShopId(shopId);
            shopCart.setShopName(shopCartItemVoList.get(0).getShopName());

            applicationContext.publishEvent(new ShopCartEvent(shopCart, shopCartItemVoList));

            shopCartVos.add(shopCart);
        }

        return shopCartVos;
    }

    @Override
    public List<ShopCartItemVo> getShopCartItemsByOrderItems(List<String> basketIdList, OrderItemParam orderItem, String userId) {
        if (orderItem == null && CollectionUtil.isEmpty(basketIdList)) {
            return Collections.emptyList();
        }

        // 当立即购买时，没有提交的订单是没有购物车信息的
        if (CollectionUtil.isEmpty(basketIdList) && orderItem != null) {

            ProdSku sku = prodSkuService.getBySkuIdCache(orderItem.getSkuId());
            if (sku == null) {
                throw new BusinessException("订单包含无法识别的商品");
            }
            Product prod = productService.getSampleProdByIdCache(orderItem.getProdId());
            if (prod == null) {
                throw new BusinessException("订单包含无法识别的商品");
            }

            // 拿到购物车的所有item
            ShopCartItemVo shopCartItemVo = new ShopCartItemVo();
            shopCartItemVo.setBasketId("-1");
            shopCartItemVo.setSkuId(orderItem.getSkuId());
            shopCartItemVo.setProdCount(orderItem.getProdCount());
            shopCartItemVo.setProdId(orderItem.getProdId());
            shopCartItemVo.setSkuName(sku.getSkuName());
            shopCartItemVo.setPic(StrUtil.isBlank(sku.getPic())? prod.getPic() : sku.getPic());
            shopCartItemVo.setProdName(sku.getProdName());
            shopCartItemVo.setProductTotalAmount(NumberUtil.multiply(sku.getPrice(), new BigDecimal(orderItem.getProdCount())));
            shopCartItemVo.setPrice(sku.getPrice());
            shopCartItemVo.setDistributionCardNo(orderItem.getDistributionCardNo());
            shopCartItemVo.setBasketDate(new Date());
            ShopDetail shopDetail = shopDetailService.getByShopIdCache(orderItem.getShopId());
            shopCartItemVo.setShopId(shopDetail.getId());
            shopCartItemVo.setShopName(shopDetail.getShopName());
            return Collections.singletonList(shopCartItemVo);
        }
        List<ShopCartItemVo> dbShopCartItems = getShopCartItems(userId);

        // 返回购物车选择的商品信息
        return dbShopCartItems.stream().filter(shopCartItemVo -> basketIdList.contains(shopCartItemVo.getId()))
                .collect(Collectors.toList());
    }


}
